package com.le.enhance.class8;

import org.junit.Test;

// 矩阵最小路径和
public class Code_06_MinPathSum {
    public static int minPath1(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        return process(matrix, 0, 0);
    }

    public static int process(int[][] arr, int i, int j) {
        if (i == arr.length - 1 && j == arr[0].length - 1) {
            return arr[i][j];
        }
        if (i == arr.length - 1) {
            return arr[i][j] + process(arr, i, j + 1);
        }
        if (j == arr[0].length - 1) {
            return arr[i][j] + process(arr, i + 1, j);
        }
        return Math.min(
                arr[i][j] + process(arr, i, j + 1),
                arr[i][j] + process(arr, i + 1, j)
        );
    }

    public static int process2(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
            return 0;
        }
        int[][] dp = new int[matrix.length][matrix[0].length];
        dp[0][0] = matrix[0][0];
        for (int row = 1; row < matrix.length; row++) {
            dp[row][0] = matrix[row][0] + dp[row - 1][0];
        }
        for (int col = 1; col < matrix[0].length; col++) {
            dp[0][col] = matrix[0][col] + dp[0][col - 1];
        }
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                dp[i][j] = matrix[i][j] + Math.min(dp[i][j - 1], dp[i - 1][j]);
            }
        }
        return dp[matrix.length - 1][matrix[0].length - 1];
    }


    @Test
    public void test() {
        int[][] arr = {
                {1, 3, 5, 9},
                {8, 1, 3, 4},
                {5, 0, 6, 1,},
                {8, 8, 4, 0}
        };
        System.out.println(minPath1(arr));
        System.out.println(process2(arr));
    }
}
